﻿using OznerOA.Common;
using OznerOA.Model;
using SufeiUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace OznerOA.BLL
{
    public class UserBLL:BaseBLL
    {
        private static UserBLL userBLL = new UserBLL();
        private string LoginUrl = "/login/VerifyLogin.jsp?isie=false&islanguid=7&loginfile=/wui/theme/ecology8/page/login.jsp%3FtemplateId%3D9%26logintype%3D1%26gopage%3D&loginid={0}&logintype=1&userpassword={1}";
        private string MainUrl = "/wui/main.jsp";
        public User LoginUser { get; set; }
        private UserBLL() { }
        #region 登录
        public BaseResult<User> Login(User user,bool autoLogin)
        {
            BaseResult<User> brMain = null;
            BaseResult<User> br = RestPostHtml<User>(string.Format(LoginUrl, user.Account, user.Password));
            if (br.Code == Code.OK)
            {
                //设置cookie
                ConfigModel.Cookies = br.HttpBaseResult.Cookie;
                brMain = GetLoginedDocument<User>(MainUrl);
                //获取相关
                if(brMain.Code == Code.OK)
                {
                    //设置User相关
                    ConfigModel.UserName = user.Account;
                    ConfigModel.Password = user.Password;
                    ConfigModel.AutoLogin = autoLogin;

                    HtmlAgilityPack.HtmlDocument doc = brMain.OtherInfo as HtmlAgilityPack.HtmlDocument;
                    FillUser(user,doc);
                    GetUserInfo(user);
                    brMain.Object = user;
                    this.LoginUser = user;
                }
            }else
            {
                brMain = new BaseResult<User>()
                {
                    Code = Code.NULL,
                    Message = br.Message
                };
            }

            return brMain;
        }

        public BaseResult<string> SavePad(string padContent)
        {
            string URL = "http://oa.ozner.net:8080/page/element/scratchpad/ScratchpadOperation.jsp";
            string data = string.Format("eid={0}&userid={1}&operation=save&padcontent={2}"
                , userBLL.LoginUser.PadcontentEid, userBLL.LoginUser.Id, padContent);
            BaseResult<string> br = GetLoginedDocument<string>(URL+"?"+data);
            if(br.Code == Code.OK)
            {
                br.Object = br.HttpBaseResult.Html.Trim();
            }
            return br;
        }
        #endregion
        #region 通过登录封装User
        /// <summary>
        /// 通过HtmlDocument封装User
        /// </summary>
        /// <param name="user"></param>
        /// <param name="doc"></param>
        private void FillUser(User user, HtmlDocument doc)
        {
            HtmlAgilityPack.HtmlNode nodeName = doc.DocumentNode.SelectSingleNode("//div[@id='leftBlock_HrmDiv']/div[1]/div[2]");
            HtmlAgilityPack.HtmlNode nodeDept = doc.DocumentNode.SelectSingleNode("//div[@id='leftBlockHrmDep']");
            HtmlAgilityPack.HtmlNode nodeChangePassword = doc.DocumentNode.SelectSingleNode("//div[@id='leftBlock_HrmDiv']/div[1]/div[@class='more']/table[1]/tr[1]/td[5]/a[1]");
            HtmlAgilityPack.HtmlNode nodePageHome = doc.DocumentNode.SelectSingleNode("//div[@id='drillmenu']/ul/li/div/a");
            if (nodeName != null)
            {
                HtmlAttribute ha = nodeName.Attributes["title"];
                if (ha != null)
                {
                    user.Name = ha.Value;
                }
            }
            if(nodeDept != null)
            {
                HtmlAttribute ha = nodeDept.Attributes["title"];
                if (ha != null)
                {
                    user.Dept = ha.Value;
                }
            }
            if (nodeChangePassword != null)
            {
                HtmlAttribute ha = nodeChangePassword.Attributes["href"];
                if (ha != null)
                {
                    user.Id = ParseAddress(ha.Value).Params["id"];
                }
            }
            if (nodePageHome != null)
            {
                HtmlAttribute ha = nodePageHome.Attributes["href"];
                if (ha != null)
                {
                    user.PageHomeUrl = ha.Value;
                }
            }
        }
        #endregion
        #region 替换字符串
        /// <summary>
        /// 取出字符
        /// </summary>
        private string ReplaceNull(string str,params string[] replace)
        {
            string res = str;
            foreach(string s in replace)
            {
                res = str.Replace(s, "");
            }
            return res;
        }
        #endregion
        #region 获取用户信息
        public BaseResult<User> GetUserInfo(User user)
        {
            string url = "/hrm/resource/simpleHrmResourceTemp.jsp";
            string postdata = string.Format("userid={0}", user.Id);
            BaseResult<User> br = GetLoginedDocument<User>(url+"?"+postdata);
            if(br.Code == Code.OK)
            {
                string[] info = br.HttpBaseResult.Html.Split(new String[] { "$$$" }, StringSplitOptions.None);
                user.Name = info[2];
                user.Sex = info[3].Contains("Mr") ? "男" : "女";
                user.Phone = info[4];
                user.Tel = info[5];
                user.Email = info[6];
                user.DeptName = info[7];
                user.ManagerName = info[8];
                user.Subsection = info[10];
                user.Ship = info[11];
                user.Status = info[12];
            }
            return br;
        }

        #endregion
        #region 获取自动便签
        public BaseResult<string> GetPad()
        {
            //先获取便签地址
            GetPadUrl();
            if (!string.IsNullOrEmpty(LoginUser.PadcontentGetUrl))
            {
                BaseResult<string> br = GetLoginedDocument<string>(LoginUser.PadcontentGetUrl);
                if (br.Code == Code.OK)
                {
                    HtmlAgilityPack.HtmlDocument doc = br.OtherInfo as HtmlDocument;
                    HtmlNode hn = doc.DocumentNode.SelectSingleNode("//div/table/tr/td/textarea");
                    if (hn != null)
                    {
                        br.Object = hn.InnerText;
                    }
                    else
                    {
                        br.Code = Code.NULL;
                        br.Message = "服务器返回数据错误!";
                        logBLL.Debug("服务器返回数据错误!\r\n" + br.HttpBaseResult.Html);
                    }
                }
                return br;
            }else
            {
                return GetResult<string>(Code.NULL, "获取便签地址失败!", "未获取到便签的地址!");
            }
        }
        #endregion
        private void GetPadUrl()
        {
            if (!string.IsNullOrEmpty(LoginUser.PageHomeUrl))
            {
                BaseResult<string> brHome = GetLoginedDocument<string>(LoginUser.PageHomeUrl);
                if (brHome.Code == Code.OK)
                {
                    HtmlDocument docHome = brHome.OtherInfo as HtmlDocument;
                    HtmlNode hnEid = docHome.DocumentNode.SelectSingleNode("//table[@id='Container']/tr/td[2]/div/div[4]");
                    HtmlNode hnUrl = docHome.DocumentNode.SelectSingleNode("//table[@id='Container']/tr/td[2]/div/div[4]/div[2]/div");
                    if (hnEid != null)
                    {
                        HtmlAttribute ha = hnEid.Attributes["eid"];
                        if (ha != null)
                        {
                            userBLL.LoginUser.PadcontentEid = ha.Value;
                        }
                    }
                    if (hnUrl != null)
                    {
                        HtmlAttribute ha = hnUrl.Attributes["url"];
                        if (ha != null)
                        {
                            userBLL.LoginUser.PadcontentGetUrl = ha.Value;
                        }
                    }
                }
            }
        }
        #region 保存自动便签
        #endregion
        #region 单例获取实例
        public static UserBLL GetInstance()
        {
            return userBLL;
        }
        #endregion
    }
}
